package com.galeno.day06;

import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/2121:07
 */
public class Demo1 {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",12345);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        /**
         * 使用过时的API
         */

        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        DataStreamSource<String> lines = env.socketTextStream("192.168.77.3", 9999);
        SingleOutputStreamOperator<Tuple3<Long, String, Integer>> tpStream = lines.map(x -> {
            String[] split = x.split(",");
            Long timestemp = Long.parseLong(split[0]);
            String words = split[1];
            int count = Integer.parseInt(split[2]);
            return Tuple3.of(timestemp, words, count);
        }).returns(TypeInformation.of(new TypeHint<Tuple3<Long, String, Integer>>() {
        }));
//        tpStream.print();
//        env.execute();
        //提取数据中的时间
        //（触发EventTime类型窗口执行的信号机制）
        //设置窗口延迟触发的时间为2秒
        SingleOutputStreamOperator<Tuple3<Long, String, Integer>> wordAndCountWithMark = tpStream.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Tuple3<Long, String, Integer>>(Time.seconds(2)) {
            @Override
            public long extractTimestamp(Tuple3<Long, String, Integer> element) {
                return element.f0;
            }
        }).setParallelism(1);
        KeyedStream<Tuple3<Long, String, Integer>, String> keyedStream = wordAndCountWithMark.keyBy(x -> {
            return x.f1;
        });

        WindowedStream<Tuple3<Long, String, Integer>, String, TimeWindow> windowedStream = keyedStream.window(TumblingEventTimeWindows.of(Time.seconds(10)));

        SingleOutputStreamOperator<Tuple3<Long, String, Integer>> sumed = windowedStream.sum(2);
        sumed.print();
        env.execute();


    }
}
